

// 服务端 socket 

// webSocket 

// 创建socket 链接指定的端口 

// 服务端socket  监听端口   监听客户端socket 发来消息  接收客户端发来的消息 把消息再转发给其他客户端      监听 关闭 error
var ws = require("ws");

var WebSocketServer = ws.Server;

var port = 4000;

var wss = new WebSocketServer({ port: port });   //创建socket 监听端口3200

var clientUserMap = {}
var count = 0;
var info = "wuhan1809_";

// 1. 监听客户端socket 链接  
wss.on("connection", (ws) => {
    count++;
    ws.name = info + count;
    clientUserMap[ws.name] = ws;

    // 2. 接收 客户端 发来的消息   把消息转发给其他的用户 
    ws.on("message", (msg) => {
        // ws.send()
        broadcast(msg, ws)
    })

    //  3. 监听客户端 关闭  close 
    ws.on("close", () => {
        delete clientUserMap[ws.name];  // 根据 key 删除某一项 
        broadcast('我下线了哦,886...', ws)
    })

})

function broadcast(msg, ws) {
    for (var key in clientUserMap) {
        clientUserMap[key].send(`${ws.name} 说 :  ${msg}  <br>`)
    }
}



